<?php
// products.php - Enhanced Product Display Page
// Student: [Your Name], ID: [Your Student ID]

/**
 * Load product data from JSON file
 */
function loadProducts() {
    $jsonFile = 'data/products.json';
    
    if (!file_exists($jsonFile)) {
        // Create sample data if file doesn't exist
        $sampleProducts = [
            [
                "id" => 1,
                "name" => "Sichuan Chili Oil",
                "image_url" => "https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?w=400",
                "price" => 15.99,
                "description" => "Authentic Sichuan style chili oil with rich aroma and perfect balance of spice",
                "supplier" => "Sichuan Specialties",
                "category" => "Sauces",
                "discount" => 10,
                "quantity" => 50,
                "origin_country" => "China",
                "spice_level" => "Very Hot",
                "rating" => 4.5,
                "review_count" => 128
            ],
            [
                "id" => 2,
                "name" => "Japanese Matcha KitKat",
                "image_url" => "https://images.unsplash.com/photo-1571091718767-18b5b1457add?w=400",
                "price" => 8.50,
                "description" => "Premium matcha green tea flavored chocolate with authentic Japanese taste",
                "supplier" => "Japanese Sweets Co.",
                "category" => "Snacks",
                "discount" => 0,
                "quantity" => 100,
                "origin_country" => "Japan",
                "spice_level" => "Not Spicy",
                "rating" => 4.2,
                "review_count" => 89
            ],
            // Add more sample products here...
        ];
        
        // Create directory if it doesn't exist
        if (!is_dir('data')) {
            mkdir('data', 0755, true);
        }
        
        file_put_contents($jsonFile, json_encode($sampleProducts, JSON_PRETTY_PRINT));
    }
    
    $productsData = file_get_contents($jsonFile);
    return json_decode($productsData, true);
}

$products = loadProducts();

// Group products by category
$categories = [];
foreach ($products as $product) {
    $category = $product['category'];
    if (!isset($categories[$category])) {
        $categories[$category] = [];
    }
    $categories[$category][] = $product;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products - Global Food Market</title>
    <link rel="stylesheet" href="css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <!-- Modern Header (same as index.php) -->
    <header class="modern-header">
        <div class="header-top">
            <div class="container">
                <div class="header-contact">
                    <span><i class="fas fa-phone"></i> +1 (555) 123-4567</span>
                    <span><i class="fas fa-envelope"></i> info@globalfoodmarket.com</span>
                </div>
                <div class="header-social">
                    <a href="#"><i class="fab fa-facebook-f"></i></a>
                    <a href="#"><i class="fab fa-instagram"></i></a>
                    <a href="#"><i class="fab fa-twitter"></i></a>
                </div>
            </div>
        </div>
        
        <nav class="main-nav">
            <div class="container">
                <div class="nav-brand">
                    <h1 class="logo">Global Food Market</h1>
                    <p class="tagline">Taste the World</p>
                </div>
                <ul class="nav-menu">
                    <li><a href="index.php" class="nav-link">Home</a></li>
                    <li><a href="products.php" class="nav-link active">Products</a></li>
                    <li><a href="about.php" class="nav-link">About</a></li>
                    <li><a href="contact.php" class="nav-link">Contact</a></li>
                    <li><a href="admin/login.php" class="nav-link admin-btn">Admin</a></li>
                </ul>
                <div class="nav-actions">
                    <button class="cart-btn">
                        <i class="fas fa-shopping-cart"></i>
                        <span class="cart-count">0</span>
                    </button>
                    <button class="mobile-menu-btn">
                        <i class="fas fa-bars"></i>
                    </button>
                </div>
            </div>
        </nav>
    </header>

    <!-- Products Header -->
    <section class="page-header">
        <div class="container">
            <h1>Our Products</h1>
            <p>Discover authentic flavors from around the world</p>
        </div>
    </section>

    <!-- Products Filter -->
    <section class="products-filter">
        <div class="container">
            <div class="filter-container">
                <div class="filter-group">
                    <label>Category:</label>
                    <select id="categoryFilter">
                        <option value="all">All Categories</option>
                        <option value="Sauces">Sauces</option>
                        <option value="Snacks">Snacks</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Sort by:</label>
                    <select id="sortFilter">
                        <option value="name">Name</option>
                        <option value="price">Price: Low to High</option>
                        <option value="price_desc">Price: High to Low</option>
                        <option value="rating">Rating</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Spice Level:</label>
                    <select id="spiceFilter">
                        <option value="all">All Levels</option>
                        <option value="Not Spicy">Not Spicy</option>
                        <option value="Mild">Mild</option>
                        <option value="Medium">Medium</option>
                        <option value="Hot">Hot</option>
                        <option value="Very Hot">Very Hot</option>
                    </select>
                </div>
            </div>
        </div>
    </section>

    <!-- Products Grid -->
    <section class="products-listing">
        <div class="container">
            <?php foreach ($categories as $categoryName => $categoryProducts): ?>
            <div class="category-section" data-category="<?php echo strtolower($categoryName); ?>">
                <h2 class="category-title">
                    <i class="fas fa-<?php echo $categoryName === 'Sauces' ? 'wine-bottle' : 'cookie'; ?>"></i>
                    <?php echo htmlspecialchars($categoryName); ?>
                </h2>
                <div class="products-grid">
                    
                    <?php foreach ($categoryProducts as $product): ?>
                    <?php
                    $discountedPrice = $product['price'] * (1 - $product['discount'] / 100);
                    $rating = $product['rating'] ?? 4.0;
                    $reviewCount = $product['review_count'] ?? 50;
                    ?>
                    <div class="product-card" 
                         data-category="<?php echo strtolower($product['category']); ?>"
                         data-spice="<?php echo strtolower(str_replace(' ', '-', $product['spice_level'])); ?>"
                         data-price="<?php echo $discountedPrice; ?>"
                         data-rating="<?php echo $rating; ?>">
                        
                        <?php if ($product['discount'] > 0): ?>
                        <div class="product-badge"><?php echo $product['discount']; ?>% OFF</div>
                        <?php endif; ?>
                        
                        <?php if ($product['quantity'] < 10): ?>
                        <div class="stock-badge low-stock">Low Stock</div>
                        <?php endif; ?>
                        
                        <div class="product-image">
                            <img src="<?php echo htmlspecialchars($product['image_url']); ?>" 
                                 alt="<?php echo htmlspecialchars($product['name']); ?>">
                            <div class="product-actions">
                                <button class="action-btn wishlist" title="Add to Wishlist">
                                    <i class="far fa-heart"></i>
                                </button>
                                <button class="action-btn quick-view" title="Quick View">
                                    <i class="far fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="product-info">
                            <span class="product-category"><?php echo htmlspecialchars($product['category']); ?></span>
                            <h3 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h3>
                            <p class="product-description"><?php echo htmlspecialchars($product['description']); ?></p>
                            
                            <div class="product-rating">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <?php if ($i <= floor($rating)): ?>
                                        <i class="fas fa-star"></i>
                                    <?php elseif ($i - 0.5 <= $rating): ?>
                                        <i class="fas fa-star-half-alt"></i>
                                    <?php else: ?>
                                        <i class="far fa-star"></i>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                <span class="rating-count">(<?php echo $reviewCount; ?>)</span>
                            </div>
                            
                            <div class="product-meta">
                                <div class="meta-item">
                                    <strong>Origin:</strong>
                                    <span class="country-flag"><?php echo htmlspecialchars($product['origin_country']); ?></span>
                                </div>
                                <div class="meta-item">
                                    <strong>Spice Level:</strong>
                                    <span class="spice-level spice-<?php echo strtolower(str_replace(' ', '-', $product['spice_level'])); ?>">
                                        <?php echo htmlspecialchars($product['spice_level']); ?>
                                    </span>
                                </div>
                                <div class="meta-item">
                                    <strong>Supplier:</strong>
                                    <span><?php echo htmlspecialchars($product['supplier']); ?></span>
                                </div>
                            </div>
                            
                            <div class="product-price">
                                <?php if ($product['discount'] > 0): ?>
                                    <span class="current-price">$<?php echo number_format($discountedPrice, 2); ?></span>
                                    <span class="original-price">$<?php echo number_format($product['price'], 2); ?></span>
                                <?php else: ?>
                                    <span class="current-price">$<?php echo number_format($product['price'], 2); ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="product-actions-bottom">
                                <button class="add-to-cart-btn" data-product-id="<?php echo $product['id']; ?>">
                                    <i class="fas fa-shopping-cart"></i>
                                    Add to Cart
                                </button>
                                <div class="quantity-controls">
                                    <button class="qty-btn minus">-</button>
                                    <span class="quantity">1</span>
                                    <button class="qty-btn plus">+</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- Modern Footer (same as index.php) -->
    <footer class="modern-footer">
        <!-- Footer content from index.php -->
    </footer>

    <script>
        // Enhanced JavaScript for products page
        document.addEventListener('DOMContentLoaded', function() {
            // Filter functionality
            const categoryFilter = document.getElementById('categoryFilter');
            const sortFilter = document.getElementById('sortFilter');
            const spiceFilter = document.getElementById('spiceFilter');
            const productCards = document.querySelectorAll('.product-card');
            const categorySections = document.querySelectorAll('.category-section');

            function applyFilters() {
                const selectedCategory = categoryFilter.value;
                const selectedSpice = spiceFilter.value;
                
                categorySections.forEach(section => {
                    const sectionCategory = section.getAttribute('data-category');
                    
                    if (selectedCategory === 'all' || selectedCategory === sectionCategory) {
                        section.style.display = 'block';
                        
                        // Filter products within this category
                        const products = section.querySelectorAll('.product-card');
                        let visibleProducts = 0;
                        
                        products.forEach(product => {
                            const productSpice = product.getAttribute('data-spice');
                            const shouldShow = selectedSpice === 'all' || selectedSpice === productSpice;
                            
                            product.style.display = shouldShow ? 'block' : 'none';
                            if (shouldShow) visibleProducts++;
                        });
                        
                        // Hide category section if no products are visible
                        section.style.display = visibleProducts > 0 ? 'block' : 'none';
                    } else {
                        section.style.display = 'none';
                    }
                });
            }

            categoryFilter.addEventListener('change', applyFilters);
            spiceFilter.addEventListener('change', applyFilters);

            // Sort functionality
            sortFilter.addEventListener('change', function() {
                const sortBy = this.value;
                
                categorySections.forEach(section => {
                    const productsContainer = section.querySelector('.products-grid');
                    const products = Array.from(section.querySelectorAll('.product-card'));
                    
                    products.sort((a, b) => {
                        switch(sortBy) {
                            case 'price':
                                return parseFloat(a.getAttribute('data-price')) - parseFloat(b.getAttribute('data-price'));
                            case 'price_desc':
                                return parseFloat(b.getAttribute('data-price')) - parseFloat(a.getAttribute('data-price'));
                            case 'rating':
                                return parseFloat(b.getAttribute('data-rating')) - parseFloat(a.getAttribute('data-rating'));
                            default:
                                return a.querySelector('.product-title').textContent.localeCompare(b.querySelector('.product-title').textContent);
                        }
                    });
                    
                    // Reappend sorted products
                    products.forEach(product => productsContainer.appendChild(product));
                });
            });

            // Add to cart functionality
            const addToCartBtns = document.querySelectorAll('.add-to-cart-btn');
            const cartCount = document.querySelector('.cart-count');
            let count = 0;

            addToCartBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    const productCard = this.closest('.product-card');
                    const productTitle = productCard.querySelector('.product-title').textContent;
                    const quantity = parseInt(productCard.querySelector('.quantity').textContent);
                    
                    count += quantity;
                    cartCount.textContent = count;
                    cartCount.classList.add('pulse');
                    
                    setTimeout(() => {
                        cartCount.classList.remove('pulse');
                    }, 500);
                    
                    showNotification(`${quantity} x ${productTitle} added to cart!`);
                    
                    // Reset quantity
                    productCard.querySelector('.quantity').textContent = '1';
                });
            });

            // Quantity controls
            document.querySelectorAll('.qty-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const quantityElement = this.parentElement.querySelector('.quantity');
                    let quantity = parseInt(quantityElement.textContent);
                    
                    if (this.classList.contains('plus')) {
                        quantity++;
                    } else if (this.classList.contains('minus') && quantity > 1) {
                        quantity--;
                    }
                    
                    quantityElement.textContent = quantity;
                });
            });

            // Wishlist functionality
            document.querySelectorAll('.wishlist').forEach(btn => {
                btn.addEventListener('click', function() {
                    this.classList.toggle('active');
                    this.innerHTML = this.classList.contains('active') ? 
                        '<i class="fas fa-heart"></i>' : 
                        '<i class="far fa-heart"></i>';
                });
            });

            function showNotification(message) {
                const notification = document.createElement('div');
                notification.className = 'notification';
                notification.innerHTML = `
                    <i class="fas fa-check-circle"></i>
                    <span>${message}</span>
                `;
                document.body.appendChild(notification);
                
                setTimeout(() => {
                    notification.classList.add('fade-out');
                    setTimeout(() => notification.remove(), 300);
                }, 3000);
            }
        });
    </script>
</body>
</html>